#include "TcpClient.h"
#include <QHostAddress>
#include <QDebug>
#include <QTimer>
#include <iostream>

TcpClient::TcpClient(QObject *parent)
    : QObject{parent}
{
    m_tcpSocket = new QTcpSocket(this);
    connect(m_tcpSocket, &QTcpSocket::connected, this, &TcpClient::onConnected);
}

void TcpClient::connectToServer(QHostAddress ip, int port)
{
    m_tcpSocket->connectToHost(ip, port);
    connect(m_tcpSocket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
}

void TcpClient::disconnectFromServer()
{
    //m_tcpSocket->disconnectFromHost();
    m_tcpSocket->abort();
    disconnect(m_tcpSocket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
}

QAbstractSocket::SocketState TcpClient::state()
{
    return m_tcpSocket->state();
}

uint32_t TcpClient::sendMessage(MessageType type, QByteArray data)
{
    QByteArray packet;
    RadarProtocol::makePacket(type, data, packet);

    m_tcpSocket->write(packet);
    qDebug()<<"send data:"<<packet.toHex(' ');

    return RadarProtocol::requestId;
}

void TcpClient::onConnected()
{
    qDebug()<<"与雷达建立连接"<<endl;
    emit connected();
}

void TcpClient::onReadyRead()
{
    QByteArray data = m_tcpSocket->readAll();
    QList<QByteArray> packetList = unpack(data);


    foreach (auto packet, packetList)
    {
        QByteArray messageData;
        MessageType type = RadarProtocol::parsePacket(packet, messageData);
        qDebug()<<"receive data---->:"<<packet.toHex(' ');


        //怎么解析这个数据是关键，这个地方的雷达数据与雷达模拟软件发送的数据不一致，因此需要分析







        switch (type) {
        case MessageType::HeartbeatRequest:
        {
            HeartbeatMessage message;
            message.parseBody(messageData);
            emit recvHeartbeatResponse(RadarProtocol::responseId);
            //std::cout<<"发送心跳信息"<<std::endl;
            break;
        }
        case MessageType::LoginRequest:
        {
            emit recvLoginResponse();
            break;
        }
        case MessageType::GetRegRequest:
        {
            GetRegResponseMessage message;
            message.parseBody(messageData);
            emit recvRegResponse(message);
            break;
        }
        case MessageType::TrackDataV2:
        {
            TrackDataV2Message message;
            message.parseBody(messageData);
            emit recvTrackDataV2(message);
            break;
        }
        case MessageType::TrackDataV3:
        {

            TrackDataV3Message message;
            message.parseBody(messageData);
            emit recvTrackDataV3(message);

            break;
        }
        case MessageType::RTKData:
        {
            RTKDataMessage message;
            message.parseBody(messageData);
            emit recvRTKData(message);
            break;
        }
        default:
            break;
        }
    }

}

QList<QByteArray> TcpClient::unpack(QByteArray &packet)
{
    int curIndex = 0;
    int32_t magic = 0;
    int32_t dataLen = 0;
    int32_t command = 0;
    int32_t frameId = 0;
    char tempArr[65536] = {0};
    int16_t crc = 0;

    QList<QByteArray> messages;

    QDataStream inStream(&packet, QIODevice::ReadOnly);
    inStream.setByteOrder(QDataStream::BigEndian);

    while (curIndex < packet.size())
    {
        inStream >> magic;
        inStream >> dataLen;
        inStream >> command;
        inStream >> frameId;
        inStream.readRawData(tempArr, dataLen-10);
        inStream >> crc;

        if (magic == headerMagic && dataLen >= minMessageLen && dataLen <= maxMessageLen)
        {
            QByteArray message;
            QDataStream outStream(&message, QIODevice::WriteOnly);
            outStream.setByteOrder(QDataStream::BigEndian);

            outStream << magic;
            outStream << dataLen;
            outStream << command;
            outStream << frameId;
            outStream.writeRawData(tempArr, dataLen-10);
            outStream << crc;

            messages.push_back(message);
        }
        else
        {
            break;
        }
        curIndex += (8+dataLen);
    }

    return messages;
}
